//
//  CameraViewController.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/4/22.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "CameraViewController.h"
#import "DBCameraView.h"
#import "DBCameraDelegate.h"
#import "ShowPhotoViewController.h"
#import "RuleViewController2.h"

@interface CameraViewController ()<DBCameraManagerDelegate,DBCameraViewDelegate>
{
 BOOL _processingPhoto;
 UIDeviceOrientation _deviceOrientation;
    NSMutableArray *_takePhotArray;
    NSMutableArray *_takePhotoArray2;
}


@property (nonatomic, strong) id customCamera;
@property (nonatomic, strong) DBCameraManager *cameraManager;
@property (nonatomic, strong) DBCameraView *cameraView;
@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _takePhotArray = [NSMutableArray array];
     _takePhotoArray2 = [NSMutableArray array];
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBarHidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];
     NSError *error;
   BOOL flag = [self.cameraManager setupSessionWithPreset:AVCaptureSessionPresetPhoto error:&error];
    if (flag) { //启动完成 添加 自定义的视图
        [self.view addSubview:self.cameraView];
    }
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.cameraManager performSelector:@selector(startRunning) withObject:nil afterDelay:0.0];
    //发送一个屏幕转变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(rotationChanged:)
                                                 name:@"UIDeviceOrientationDidChangeNotification"
                                               object:nil];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
}

- (void)startRunning
{
    
}
- (DBCameraView *)cameraView
{
    if(!_cameraView){
        _cameraView = [DBCameraView initWithCaptureSession:self.cameraManager.captureSession];//
        _cameraView.isHaveRuleBtn = self.isHaveRuleBtn;
        _cameraView.delegate = self;
        [_cameraView defaultInterface];//添加一些按钮到cameraView上
    }
    
    return _cameraView;
}

- (DBCameraManager *)cameraManager
{
    if (!_cameraManager) {
        _cameraManager = [[DBCameraManager alloc] init];
        _cameraManager.delegate = self;
    }
    return _cameraManager;
}
- (void) rotationChanged:(NSNotification *)notification
{
    if ( [[UIDevice currentDevice] orientation] != UIDeviceOrientationUnknown ||
        [[UIDevice currentDevice] orientation] != UIDeviceOrientationFaceUp ||
        [[UIDevice currentDevice] orientation] != UIDeviceOrientationFaceDown ) {
        _deviceOrientation = [[UIDevice currentDevice] orientation];
    }
}
#pragma mark - CameraManagerDelagate

- (void)closeCamera
{
    if(self.isPush == NO){

    [self dismissViewControllerAnimated:NO completion:nil];
    return;
   }

    [self.navigationController popViewControllerAnimated:NO];
//    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)switchCamera
{
    if ([self.cameraManager hasMultipleCameras]) {//判断 设备是否有多个
        [self.cameraManager cameraToggle];//切换设备
    }
}
- (void) triggerFlashForMode:(AVCaptureFlashMode)flashMode
{
    if ( [self.cameraManager hasFlash] )
        [self.cameraManager setFlashMode:flashMode];
}
- (void) captureImageDidFinish:(UIImage *)image
{
    NSData *data;
    data =[self imageWithImage:image scaledToSize:CGSizeMake(kScreenWidth  - 10 * [UIView getWidth:8.0f], (kScreenWidth  - 10 * [UIView getWidth:8.0f]) * 1000 / 800 ) withScale:0.5];
//    NSData *data1 =UIImageJPEGRepresentation(image, 0.1);
    NSData *data1;
    data1 = [self imageWithImage:image scaledToSize:CGSizeMake((kScreenWidth - 5.0f * 3) / 4.0f, (kScreenWidth - 5 * 3) / 4.0f) withScale:0.1];
////    if (_isAddRecordCamera) {
//        [self dismissViewControllerAnimated:NO completion:^{
//            self.backBlock(data,data1);
//        }];
//    }else{
    if (_isShouldBack) {
//           self.backBlock(data,data1);
//        [self.navigationController popViewControllerAnimated:NO];
     

        [self dismissViewControllerAnimated:NO completion:^{
             self.backBlock(data,data1);
        }];
    }else{
        _processingPhoto = NO;
//        NSData *data = UIImageJPEGRepresentation(image, 0.4);
        //    NSLog(@"imageData%@",);
        [_takePhotArray addObject:data];
       [_takePhotoArray2 addObject:data1];
        
        NSLog(@"相机拍摄完成后数组的个数%d",_takePhotArray.count);
        ShowPhotoViewController *showPhoto = [[ShowPhotoViewController alloc] init];
        showPhoto.imageArr = _takePhotArray;
        
        showPhoto.iamgeSmallArr = _takePhotoArray2;
        //     [self performSelector:@selector(dealImage) withObject:nil afterDelay:1.0f];
//        UINavigationController *nav= [[UINavigationController alloc] initWithRootViewController:showPhoto];
        showPhoto.checkType = self.checkType;
        showPhoto.branchId = self.branchId;
        showPhoto.checkID =self.checkId;
        showPhoto.checkDetailId = self.detailID;
        showPhoto.upLoadNumber = self.uploadNum;//上传图片数量限制
        [self.navigationController pushViewController:showPhoto animated:NO];
        //    [self performSelector:@selector(dealImage) withObject:nil afterDelay:1.0f];
    }
//    }
 
}

- (NSData *)imageWithImage:(UIImage*)image
              scaledToSize:(CGSize)newSize withScale:(CGFloat)scale;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, scale);
}
- (void)clickToPresentRuleVC
{
    RuleViewController2 * cv = [[RuleViewController2 alloc] init];//wwrr
    cv.inCameraChoose = YES;
    cv.ruleType = self.checkType;
////    cv.check_id = ;

    cv.branach_Id = self.branchId;
    cv.check_id = self.checkId;

    [self presentViewController:cv animated:YES completion:nil];
//    [self.navigationController popViewControllerAnimated:NO];
}
- (void)pinchToScaleTakePhotoWithPointWith:(CGFloat)scale with:(AVCaptureVideoPreviewLayer *)previewlayer
{
//    if ([self.cameraManager pinchToScaleWithScale:scale withlayer:previewlayer]) {
        [self.cameraManager pinchToScaleWithScale:scale withlayer:previewlayer];
//    }
}


- (void) captureImageFailedWithError:(NSError *)error
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] show];
    });
}

- (void)captureSessionDidStartRunning
{
    CGRect bounds = _cameraView.bounds;
    AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)_cameraView.layer;
     CGPoint screenCenter = (CGPoint){ (bounds.size.width * .5f), (bounds.size.height * .5f) - CGRectGetMinY(previewLayer.frame) };
    
    if ([_cameraView respondsToSelector:@selector(drawFocusBoxAtPointOfInterest:andRemove:)] )
        [_cameraView drawFocusBoxAtPointOfInterest:screenCenter andRemove:NO];
    if ( [_cameraView respondsToSelector:@selector(drawExposeBoxAtPointOfInterest:andRemove:)] )
        [_cameraView drawExposeBoxAtPointOfInterest:screenCenter andRemove:NO];
    
}
#pragma mark - CameraViewDelagate
- (void) cameraViewStartRecording
{
    if ( _processingPhoto )
        return;
    
    _processingPhoto = YES;
    
    [self.cameraManager captureImageForDeviceOrientation:_deviceOrientation];
}

- (void) cameraView:(UIView *)camera focusAtPoint:(CGPoint)point
{
    if ( self.cameraManager.videoInput.device.isFocusPointOfInterestSupported ) {
        [self.cameraManager focusAtPoint:[self.cameraManager convertToPointOfInterestFrom:[[(DBCameraView *)camera previewLayer] frame] coordinates:point layer:[(DBCameraView *)camera previewLayer]]];
        [(DBCameraView *)camera drawFocusBoxAtPointOfInterest:point andRemove:YES];
    }
}

- (void) cameraView:(UIView *)camera exposeAtPoint:(CGPoint)point
{
    if ( self.cameraManager.videoInput.device.isExposurePointOfInterestSupported ) {
        [self.cameraManager exposureAtPoint:[self.cameraManager convertToPointOfInterestFrom:[[(DBCameraView *)camera previewLayer] frame]coordinates:point layer:[(DBCameraView *)camera previewLayer]]];
        [(DBCameraView *)camera drawExposeBoxAtPointOfInterest:point andRemove:YES];
    }
}
#pragma mark - UIApplicationDidEnterBackgroundNotification

- (void) applicationDidEnterBackground:(NSNotification *)notification
{
    id modalViewController = self.presentingViewController;
    if ( modalViewController )
        [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载，在WWDC视频也忽视这一点。
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }
    
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//                       NSLog(@"files :%d",[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       };});
    [[SDImageCache sharedImageCache] clearDisk];//清理磁盘

    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    _takePhotArray = nil;
    _takePhotoArray2 = nil;
}
- (BOOL)prefersStatusBarHidden
{
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
